<template>
  <div class="public_height100 p20 pub_bgColorFFF">
    <div class="crumbs flex_start">
      <span class="crumbs_active" @click="goPage('layout/orderManagement')">订单管理</span>
      <img src="@/assets/img/customer/crumbs_next.png" alt="返回" class="pub_imgSize16 ml8" />
      <span class="ml8 crumbs_active" @click="goPage('layout/orderInfo')">订单信息</span>
      <img src="@/assets/img/customer/crumbs_next.png" alt="返回" class="pub_imgSize16 ml8" />
      <span class="ml8 ">选择客户</span>
    </div>
    <!-- ====== 表格上方的筛选条件 start ======-->
    <div class="table flex_space_between mt34">
      <div class="table_list">
        <div class="table_listHeader flex_space_between">
          <span>选择客户</span>
          <el-button type="text" class="pub_button public_1EB398_btn" size="mini" @click="showDilogBtn('addDialogVisible')">+ 添加客户</el-button>
        </div>
        <div class="table_search mt12">
          <el-input v-model="params.commonSearch" class="pub_input pub_input_search" placeholder="搜索客户" clearable @keydown.enter.stop="handleSearch" @clear="handleSearch">
            <img slot="prefix" src="@/assets/img/orderManagement/search.png" class="pub_imgSize16" />
          </el-input>
        </div>
        <ul class="table_customer mt16">
          <li v-for="(item, index) in tableData" :key="index" class="flex_space_between" :class="[item.selected ? 'active' : '']" @click="selectedCustomer(item)">
            <div class="flex_center_columnStart">
              <div>
                <span>客户名称：</span>
                <span>{{ item.customerName }}</span>
              </div>
              <div>
                <span>单位地址：</span>
                <span>{{ item.customerAddress }}</span>
              </div>
            </div>
            <div class="flex_center table_group">
              <el-button type="text" class="pub_button public_4D5464_btn" size="mini" @click.stop="editBtnClick(item)"><i class="el-icon-edit"></i></el-button>
              <el-button type="text" class="pub_button public_4D5464_btn" size="mini" @click.stop="delBtnClick(item)"><i class="el-icon-delete"></i></el-button>
            </div>
          </li>
          <PageEmptyData v-if="tableData.length === 0"></PageEmptyData>
        </ul>
      </div>
      <div class="table_list">
        <div class="table_listHeader flex_space_between">
          <span>选择课题组</span>
          <el-button v-if="groupParams.customerId" type="text" class="pub_button public_1EB398_btn" size="mini" @click="showDilogBtn('addGroupDialogVisible')">+ 添加课题组</el-button>
        </div>
        <div class="table_search mt12">
          <el-input v-model="groupParams.commonSearch" class="pub_input pub_input_search" placeholder="搜索课题组" clearable @keydown.enter.stop="groupHandleSearch" @clear="groupHandleSearch">
            <img slot="prefix" src="@/assets/img/orderManagement/search.png" class="pub_imgSize16" />
          </el-input>
        </div>
        <ul class="table_customer mt16">
          <li v-for="(item, index) in groupTableData" :key="index" class="flex_space_between" :class="[item.selected ? 'active' : '']" @click="selectedGroup(item)">
            <div>
              <span>课题组名称：</span>
              <span>{{ item.researchGroupName }}</span>
            </div>
            <div v-if="item.researchGroupName !== '默认课题组'" class="flex_center table_group">
              <el-button type="text" class="pub_button public_4D5464_btn" size="mini" @click.stop="editGroupBtnClick(item)"><i class="el-icon-edit"></i></el-button>
              <el-button type="text" class="pub_button public_4D5464_btn" size="mini" @click.stop="delGroupBtnClick(item)"><i class="el-icon-delete"></i></el-button>
            </div>
          </li>
          <PageEmptyData v-if="groupTableData.length === 0"></PageEmptyData>
        </ul>
      </div>
      <div class="table_list">
        <div class="table_listHeader flex_space_between">
          <span>选择采购人</span>
          <el-button v-if="purchaserParams.id" type="text" class="pub_button public_1EB398_btn" size="mini" @click="showDilogBtn('addPurchaserDialogVisible')">+ 添加采购人</el-button>
        </div>
        <div class="table_search mt12">
          <el-input v-model="purchaserParams.commonSearch" class="pub_input pub_input_search" placeholder="搜索课题组" clearable @keydown.enter.stop="purchaserHandleSearch" @clear="purchaserHandleSearch">
            <img slot="prefix" src="@/assets/img/orderManagement/search.png" class="pub_imgSize16" />
          </el-input>
        </div>
        <ul class="table_customerPurchaser  mt16">
          <li v-for="(item, index) in purchaserTableData" :key="index" class="flex_space_between" :class="[item.selected ? 'active' : '']" @click="selectedPurchaser(item)">
            <div class="flex_start">
              <img v-if="item.selected === false" class="img" src="@/assets/img/orderManagement/unchecked_icon.png" />
              <img v-else class="img" src="@/assets/img/orderManagement/checked_icon.png" />
              <div class="nameBox flex_center ml10">
                {{ item.customerPurchaserName.slice(-2) }}
              </div>
              <div class="flex_center_columnStart purchaser_info ml10">
                <div class="purchaserName">
                  <span>{{ item.customerPurchaserName }}</span>
                </div>
                <div class="purchaserPhone">
                  <span>{{ item.customerPurchaserPhone }}</span>
                </div>
              </div>
            </div>
            <div class="flex_center">
              <el-button type="text" class="pub_button public_4D5464_btn" size="mini" @click.stop="editPurchaserBtnClick(item)"><i class="el-icon-edit"></i></el-button>
              <el-button type="text" class="pub_button public_4D5464_btn" size="mini" @click.stop="delPurchaserBtnClick(item)"><i class="el-icon-delete"></i></el-button>
            </div>
          </li>
          <PageEmptyData v-if="purchaserTableData.length === 0"></PageEmptyData>
        </ul>
      </div>
    </div>
    <!-- ====== 表格上方的筛选条件 end ======-->
    <div class="mt20 fle">
      <el-button type="text" class="public_e0e2e7_btn pub_button" @click="handleClose">取消</el-button>
      <el-button type="text" class="public_confirm_btn pub_button" @click="submitBtnClick"> 提交 </el-button>
    </div>
    <!-- 删除提示 -->
    <deleteDialog :multiple-selection="multipleSelection" :visible="deleteDialogVisible" @close="closeDialog" @submit="confirmDelete" />
    <!-- 添加客户 -->
    <PageDialog :title="addParams.id ? '编辑客户' : '添加客户'" :dialog-visible="addDialogVisible" :width="`${$f * 600}px`" @close="closeDialog" @submit="confirmAdd">
      <el-form ref="customerRuleForm" :model="addParams" :rules="rules" label-width="5rem" class="pub_form_item">
        <el-form-item label="客户单位" prop="customerName">
          <el-input v-model="addParams.customerName" placeholder="请输入客户单位" class="pub_input" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="单位地址" prop="customerAddress">
          <el-input v-model="addParams.customerAddress" placeholder="请输入单位地址" class="pub_input" :maxlength="30"></el-input>
        </el-form-item>
      </el-form>
    </PageDialog>
    <!-- 删除课题组提示 -->
    <deleteDialog :multiple-selection="multipleSelection" :visible="deleteDialogVisible" @close="closeDialog" @submit="confirmGroupDelete" />
    <!-- 添加课题组 -->
    <PageDialog :title="addGroupParams.id ? '编辑课题组' : '添加课题组'" :dialog-visible="addGroupDialogVisible" :width="`${$f * 600}px`" @close="closeDialog" @submit="confirmAddGroup">
      <el-form ref="groupRuleForm" :model="addGroupParams" :rules="groupRules" label-width="6rem" class="pub_form_item">
        <el-form-item label="课题组名称" prop="researchGroupName">
          <el-input v-model="addGroupParams.researchGroupName" placeholder="请输入课题组名称" class="pub_input" :maxlength="10"></el-input>
        </el-form-item>
      </el-form>
    </PageDialog>
    <!-- 删除采购人提示 -->
    <deleteDialog :multiple-selection="multipleSelection" :visible="deletePurchaserDialogVisible" @close="closeDialog" @submit="confirmPurchaserDelete" />
    <!-- 添加采购人 -->
    <PageDialog :title="addPurchaserParams.id ? '编辑采购人' : '添加采购人'" :dialog-visible="addPurchaserDialogVisible" :width="`${$f * 600}px`" @close="closeDialog" @submit="confirmPurchaserAdd">
      <el-form ref="purchaserRuleForm" :model="addPurchaserParams" :rules="purchaserRules" label-width="3.75rem" class="pub_form_item">
        <el-form-item label="姓名" prop="customerPurchaserName">
          <el-input v-model="addPurchaserParams.customerPurchaserName" placeholder="请输入姓名" class="pub_input" :maxlength="5"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="customerPurchaserPhone">
          <el-input v-model="addPurchaserParams.customerPurchaserPhone" placeholder="请输入电话" class="pub_input" :maxlength="11"></el-input>
        </el-form-item>
      </el-form>
    </PageDialog>
  </div>
</template>
<script>
import PageEmptyData from '@/components/PageEmptyData/index.vue';
import PageDialog from '@/components/PageDialog/index.vue';
import deleteDialog from '@/components/deleteDialog.vue';
import { debounce } from '@/utils/debounce.js';
export default {
  components: { deleteDialog, PageEmptyData, PageDialog },
  data() {
    return {
      addPurchaserDialogVisible: false,
      deletePurchaserDialogVisible: false,
      addGroupDialogVisible: false,
      deleteDialogVisible: false, //删除弹窗是否显示
      addDialogVisible: false, //添加客户弹窗是否显示
      // 客户表单验证规则
      rules: {
        customerName: [
          { required: true, message: '请输入客户单位', trigger: 'blur' },
          { max: 20, message: '客户单位不能超过20个字符', trigger: 'blur' }
        ],
        customerAddress: [
          { required: true, message: '请输入单位地址', trigger: 'blur' },
          { max: 30, message: '单位地址不能超过30个字符', trigger: 'blur' }
        ]
      },
      // 课题组表单验证规则
      groupRules: {
        researchGroupName: [
          { required: true, message: '请输入课题组名称', trigger: 'blur' },
          { max: 10, message: '课题组名称不能超过10个字符', trigger: 'blur' }
        ]
      },
      // 采购人表单验证规则
      purchaserRules: {
        customerPurchaserName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { max: 5, message: '姓名不能超过5个字符', trigger: 'blur' }
        ],
        customerPurchaserPhone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { max: 11, message: '电话不能超过11个字符', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码格式', trigger: 'blur' }
        ]
      },
      addParams: {
        //添加客户参数
        customerAddress: '',
        customerName: ''
      },
      addGroupParams: {
        //添加课题组
        researchGroupName: ''
      },
      addPurchaserParams: {
        //添加采购人
        customerPurchaserPhone: '',
        customerPurchaserName: ''
      },
      multipleSelection: [], //选中的表格数据
      selectedRow: {}, //当前选择的数据
      params: {
        //列表请求参数
        commonSearch: ''
      },
      tableData: [],
      dataListOrg: [],
      groupParams: {
        //课题组请求参数
        customerId: '',
        commonSearch: ''
      },
      groupTableData: [],
      groupDataListOrg: [],
      purchaserParams: {
        //采购商请求参数
        commonSearch: ''
      },
      purchaserDataListOrg: [],
      purchaserTableData: [],
      sourceType: null //1：新增订单 2：编辑 3：查看详情
    };
  },
  created() {
    this.sourceType = this.$route.query.sourceType;
    this.getDataList();
  },
  methods: {
    //清空数据
    resetData(type) {
      if (type == 1) {
        this.groupTableData = [];
        this.groupDataListOrg = [];
      }
      this.purchaserDataListOrg = [];
      this.purchaserTableData = [];
    },
    //获取客户
    async getDataList() {
      let res = await this.$api.get(this.$url.customerAll, this.params);
      res.data.forEach((el, index) => {
        el.selected = index === 0;
      });
      this.tableData = res.data;
      this.dataListOrg = res.data;
      if (this.tableData.length > 0) {
        this.groupParams.customerId = this.tableData[0].id;
        this.getGroupDataList();
      }
    },
    //获取课题组数据
    async getGroupDataList() {
      let res = await this.$api.get(this.$url.researchGroupAll, { customerId: this.groupParams.customerId });
      let info = { id: this.groupParams.customerId, researchGroupName: '默认课题组' };
      [info, ...res.data].forEach((el, index) => {
        el.selected = index === 0;
      });
      this.groupTableData = [info, ...res.data];
      this.groupDataListOrg = [info, ...res.data];
      this.resetData();
      if (this.groupTableData.length > 0) {
        this.purchaserParams.id = this.groupTableData[0].id;
        this.getPurchaserDataList();
      }
    },
    //获取采购人数据
    async getPurchaserDataList() {
      let url = '';
      if (this.purchaserParams.id === this.groupParams.customerId) {
        url = this.$url.purchaserByCustomerId;
        this.purchaserParams.customerId = this.purchaserParams.id;
      } else {
        url = this.$url.purchaserByResearchGroupId;
        this.purchaserParams.researchGroupId = this.purchaserParams.id;
      }
      let res = await this.$api.get(url, this.purchaserParams);
      res.data.forEach(item => {
        item.selected = false;
      });
      this.purchaserTableData = res.data;
      this.purchaserDataListOrg = res.data;
    },
    //搜素客户
    handleSearch() {
      this.tableData = this.dataListOrg.filter(item => item.customerName.indexOf(this.params.commonSearch) !== -1 || item.customerAddress.indexOf(this.params.commonSearch) !== -1);
      this.tableData.forEach((item, index) => {
        item.selected = index === 0;
      });
      if (this.tableData.length > 0) {
        this.groupParams.customerId = this.tableData[0].id;
        this.getGroupDataList();
      }
      this.resetData(1);
    },
    //选择客户
    selectedCustomer(row) {
      this.tableData.forEach(item => {
        item.selected = false;
      });
      row.selected = true;
      this.groupParams.customerId = row.id;
      this.getGroupDataList();
      this.resetData(1);
    },
    //搜索课题组
    groupHandleSearch() {
      this.groupTableData = this.groupDataListOrg.filter(item => item.researchGroupName.indexOf(this.groupParams.commonSearch) !== -1);
      if (this.groupTableData.length > 0) {
        this.purchaserParams.id = this.groupTableData[0].id;
        this.getPurchaserDataList();
      }
      this.resetData();
    },
    //选择课题组
    selectedGroup(row) {
      this.groupTableData.forEach(item => {
        item.selected = false;
      });
      row.selected = true;
      this.purchaserParams.id = row.id;
      this.getPurchaserDataList();
      this.resetData();
    },
    //选择采购人
    selectedPurchaser(row) {
      this.purchaserTableData.forEach(item => {
        item.selected = false;
      });
      row.selected = true;
    },
    //搜索采购人
    purchaserHandleSearch() {
      this.purchaserTableData = this.dataListOrg.filter(item => item.customerPurchaserName.indexOf(this.purchaserParams.commonSearch) !== -1 || item.customerPurchaserPhone.indexOf(this.purchaserParams.commonSearch) !== -1);
    },
    //页面跳转
    goPage(pageUrl) {
      this.$router.push({
        path: '/' + pageUrl,
        query: {
          activeIndex: '1',
          sourceType: this.sourceType
        }
      });
    },
    //确认
    submitBtnClick: debounce(function() {
      let purchaserInfo = this.purchaserTableData.find(item => item.selected);
      if (purchaserInfo == undefined) {
        return this.$message.warning('请选择采购人');
      }
      let groupInfo = this.groupTableData.find(item => item.selected);
      let customerInfo = this.tableData.find(item => item.selected);
      let selectedInfo = {
        customerName: customerInfo.customerName, //客户
        customerPurchaserName: purchaserInfo.customerPurchaserName, //采购人
        customerPurchaserPhone: purchaserInfo.customerPurchaserPhone,
        researchGroupName: groupInfo.researchGroupName //课题组
      };
      window.sessionStorage.setItem('customerInfo', JSON.stringify(selectedInfo));
      this.handleClose();
    }, 500),
    handleClose() {
      this.goPage('layout/orderInfo');
    },
    //显示弹窗
    showDilogBtn(field) {
      this[field] = !this[field];
    },
    //关闭弹窗
    closeDialog() {
      this.addPurchaserDialogVisible = false;
      this.deletePurchaserDialogVisible = false;
      this.addGroupDialogVisible = false;
      this.addDialogVisible = false;
      this.deleteDialogVisible = false;
      this.addPurchaserParams = Object.assign({}, this.$options.data().addPurchaserParams);
      this.addGroupParams = Object.assign({}, this.$options.data().addGroupParams);
      this.addParams = Object.assign({}, this.$options.data().addParams); //重置参数
    },
    //确认添加客户
    async confirmAdd() {
      this.$refs.customerRuleForm.validate(async (valid) => {
        if (valid) {
          let { id } = this.addParams;
          let url = id ? this.$url.customerUpdate : this.$url.customerAdd;
          let res = await this.$api.post(url, this.addParams);
          if (res.code === 200) {
            this.closeDialog();
            this.getDataList();
            this.$message.success(id ? '更新成功' : '新增成功');
          }
        }
      });
    },
    //编辑客户
    editBtnClick(item) {
      this.addParams = Object.assign({}, item);
      this.showDilogBtn('addDialogVisible');
    },
    //删除客户
    delBtnClick(val) {
      this.selectedRow = JSON.parse(JSON.stringify(val));
      this.showDilogBtn('deleteDialogVisible');
    },
    //确认删除客户
    async confirmDelete() {
      let res = null;
      if (this.multipleSelection.length > 0 && this.selectedRow === null) {
        let idArr = this.multipleSelection.map(val => val.id);
        res = await this.$api.post(this.$url.customerDeleteBatch, idArr);
      } else {
        res = await this.$api.post(this.$url.customerDelete, { id: this.selectedRow.id });
      }
      this.closeDialog();
      if (res.code === 200) {
        this.$message.success('删除成功');
        this.getDataList();
      } else {
        this.$message.success('删除失败');
      }
    },
    //添加课题组
    async confirmAddGroup() {
      this.$refs.groupRuleForm.validate(async (valid) => {
        if (valid) {
          let { id } = this.addGroupParams;
          let url = id ? this.$url.researchGroupUpdate : this.$url.researchGroupAdd;
          this.addGroupParams.customerId = this.groupParams.customerId;
          let res = await this.$api.post(url, this.addGroupParams);
          if (res.code === 200) {
            this.closeDialog();
            this.getGroupDataList();
            this.$message.success(id ? '更新成功' : '新增成功');
          }
        }
      });
    },
    //编辑课题组
    editGroupBtnClick(item) {
      this.addGroupParams = Object.assign({}, item);
      this.showDilogBtn('addGroupDialogVisible');
    },
    //删除课题组
    delGroupBtnClick(val) {
      this.selectedRow = JSON.parse(JSON.stringify(val));
      this.showDilogBtn('deleteDialogVisible');
    },
    //确认删除课题组
    async confirmGroupDelete() {
      let res = null;
      if (this.multipleSelection.length > 0 && this.selectedRow === null) {
        let idArr = this.multipleSelection.map(val => val.id);
        res = await this.$api.post(this.$url.researchGroupDeleteBatch, idArr);
      } else {
        res = await this.$api.post(this.$url.researchGroupDelete, { id: this.selectedRow.id });
      }
      this.closeDialog();
      if (res.code === 200) {
        this.$message.success('删除成功');
        this.getGroupDataList();
      } else {
        this.$message.success('删除失败');
      }
    },
    //添加采购人
    async confirmPurchaserAdd() {
      this.$refs.purchaserRuleForm.validate(async (valid) => {
        if (valid) {
          let { id } = this.addPurchaserParams;
          let url = id ? this.$url.purchaserUpdate : this.$url.purchaserAdd;
          let findObj = this.groupTableData.find(item => {
            return item.selected == true;
          });
          if (findObj.researchGroupName === '默认课题组') {
            this.addPurchaserParams.customerId = this.purchaserParams.id;
          } else {
            this.addPurchaserParams.researchGroupId = this.purchaserParams.id;
          }
          let res = await this.$api.post(url, this.addPurchaserParams);
          if (res.code === 200) {
            this.closeDialog();
            this.getPurchaserDataList();
            this.$message.success(id ? '更新成功' : '新增成功');
          }
        }
      });
    },
    //删除采购人
    async confirmPurchaserDelete() {
      let res = null;
      if (this.multipleSelection.length > 0 && this.selectedRow === null) {
        let idArr = this.multipleSelection.map(val => val.id);
        res = await this.$api.post(this.$url.customerPurchaserDeleteBatch, idArr);
      } else {
        res = await this.$api.post(this.$url.purchaserDelete, { id: this.selectedRow.id });
      }
      this.closeDialog();
      if (res.code === 200) {
        this.$message.success('删除成功');
        this.getPurchaserDataList();
      } else {
        this.$message.success('删除失败');
      }
    },
    //编辑采购人
    editPurchaserBtnClick(item) {
      this.addPurchaserParams = Object.assign({}, item);
      this.showDilogBtn('addPurchaserDialogVisible');
    },
    //删除采购人
    delPurchaserBtnClick(val) {
      this.selectedRow = JSON.parse(JSON.stringify(val));
      this.showDilogBtn('deletePurchaserDialogVisible');
    }
  }
};
</script>
<style lang="less" scoped>
.table {
  width: 100%;
  height: calc(100% - 120px);
  border: 1px solid #e0e2e7;
  .table_list {
    width: 33.33%;
    height: 100%;
    & + .table_list {
      border-left: 1px solid #e0e2e7;
      box-sizing: border-box;
    }
    .table_listHeader {
      height: 48px;
      background: #f4f5f6;
      border-radius: 0px 0px 0px 0px;
      padding: 14px;
      font-size: 14px;
      color: #4d5464;
      box-sizing: border-box;
    }
    .table_customer,
    .table_search {
      width: 100%;
      padding: 0px 12px;
      box-sizing: border-box;
    }
    .table_customerPurchaser,
    .table_customer {
      height: calc(100% - 120px);
      overflow-y: auto;
    }
    .table_customerPurchaser li,
    .table_customer > li {
      width: 100%;
      box-sizing: border-box;
      padding: 12px 16px;
      font-size: 14px;
      cursor: pointer;
      & + li {
        margin-top: 5px;
      }
    }
    .table_customer > li {
      color: #4d5464;
      border-left: 3px solid #fff;
      &.active,
      &:hover {
        background: #f4f5f6;
        border-left: 3px solid #1eb398;
      }
      &.active {
        .table_group {
          display: flex;
        }
      }
      .table_group {
        display: none;
      }
    }
    .table_customerPurchaser li {
      img {
        width: 20px;
        height: 20px;
      }
      .purchaser_info,
      .nameBox {
        height: 37px;
      }
      .nameBox {
        width: 37px;
        background: rgba(39, 193, 165, 0.1);
        border-radius: 50%;
        border: 1px solid rgba(39, 193, 165, 0.1);
        font-size: 12px;
        color: #1eb398;
        font-weight: 600;
      }
      .purchaserName {
        font-weight: 500;
        font-size: 14px;
        font-weight: 600;
      }
      .purchaserPhone {
        font-size: 12px;
        color: #667085;
      }
      .purchaser_info.flex_center_columnStart {
        justify-content: space-between;
      }
    }
  }
}
.public_4D5464_btn,
.public_1EB398_btn {
  height: auto;
  line-height: 1;
}
</style>
